from fastapi import APIRouter
from pydantic import BaseModel,Field,field_validator
from typing import Union,Optional


router = APIRouter()

class Address(BaseModel):
    city: str
    street: str

class User(BaseModel):
    # name: str = Field(regex="^[a-zA-Z0-9]+$") # 设置name为字母和数字的组合，详细说明Field用法
    name: str
    age: int = Field(default=18,gt=0,lt=100) # 设置年龄范围，详细说明Field用法
    email: Optional[str] = None # 设置email为可选参数
    friends: list[int] = []
    addr: Address # 组合嵌套


    @field_validator("name")
    def validate_name(cls,value):
        assert value.isalpha(),"name must be alphabetic"
        return value

class Data(BaseModel): # 组合嵌套
    data: list[User]

@router.post("/user")
def user(user: User):

    print(user.model_dump())
    return {
        "message": "Hello World",
        "data": user
    }

@router.post("/data")
def data(data: Data):
    return {
        "message": "Hello World",
        "data": data
    }




